package com.ydj.app.service;

import com.ydj.app.entity.CmsAccount;
import com.ydj.app.entity.CsQrCode;
import com.ydj.app.entity.dao.CsQrCodeDao;
import com.ydj.app.entity.query.CsQrCodeQuery;
import com.ydj.app.protocol.http.cms.*;
import com.ydj.app.protocol.http.web.WebCsQrCodeGetRes;
import com.ydj.framework.exception.CommonException;
import com.ydj.framework.mysql.PageArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 客服二维码服务
 */
@Slf4j
@Service
public class CsQrCodeService {
    @Autowired
    CsQrCodeDao csQrCodeDao;

    /**
     * 列表
     */
    public CmsCsQrCodeListRes cmsList(CmsCsQrCodeListReq req, CmsAccount account) {
        PageArgs pageArgs = req.getPageArgs();

        List<CsQrCode> list = new CsQrCodeQuery(csQrCodeDao)
                .page(pageArgs);

        CmsCsQrCodeListRes res = new CmsCsQrCodeListRes(pageArgs);
        for (CsQrCode csQrCode : list) {
            CmsCsQrCodeListRes.CmsCsQrCodeListResItem item = new CmsCsQrCodeListRes.CmsCsQrCodeListResItem()
                    .setId(csQrCode.getId())
                    .setName(csQrCode.getName())
                    .setImage(csQrCode.getImage());
            res.getList().add(item);
        }
        return res;
    }

    /**
     * 新增
     */
    public CmsCsQrCodeCreateRes cmsCreate(CmsCsQrCodeCreateReq req, CmsAccount account) {
        CsQrCode csQrCode = new CsQrCode()
                .setName(req.getName())
                .setImage(req.getImage());

        csQrCodeDao.saveOrUpdate(csQrCode);

        return new CmsCsQrCodeCreateRes()
                .setId(csQrCode.getId());
    }

    /**
     * 修改
     */
    public void cmsUpdate(CmsCsQrCodeUpdateReq req, CmsAccount account) throws CommonException {
        CsQrCode csQrCode = new CsQrCodeQuery(csQrCodeDao)
                .id(req.getId())
                .single();
        CommonException.throwExceptionIfNull(csQrCode, "二维码不存在");

        csQrCode.setName(req.getName())
                .setImage(req.getImage());

        csQrCodeDao.saveOrUpdate(csQrCode);
    }

    /**
     * 删除
     */
    public void cmsDelete(CmsCsQrCodeDeleteReq req, CmsAccount account) throws CommonException {
        CsQrCode csQrCode = new CsQrCodeQuery(csQrCodeDao)
                .id(req.getId())
                .single();
        CommonException.throwExceptionIfNull(csQrCode, "二维码不存在");

        csQrCodeDao.removeById(req.getId());
    }

    /**
     * 获取客服二维码
     */
    public WebCsQrCodeGetRes webGet() throws CommonException {
        List<CsQrCode> list = new CsQrCodeQuery(csQrCodeDao).list();
        CommonException.throwExceptionIfTrue(list.isEmpty(), "客服二维码还没有配置");

        String image = list.get(0).getImage();
        return new WebCsQrCodeGetRes()
                .setImage(image);

    }
}